package com.hibiscusking.org.service.impl;

import com.hibiscusking.basic.config.BussinessException;
import com.hibiscusking.basic.query.BaseQuery;
import com.hibiscusking.basic.service.impl.BaseServiceImpl;
import com.hibiscusking.basic.util.*;
import com.hibiscusking.org.domain.Employee;
import com.hibiscusking.org.domain.Shop;
import com.hibiscusking.org.domain.ShopAuditLog;
import com.hibiscusking.org.enm.ShopState;
import com.hibiscusking.org.mapper.EmployeeMapper;
import com.hibiscusking.org.mapper.ShopAuditLogMapper;
import com.hibiscusking.org.mapper.ShopMapper;
import com.hibiscusking.org.service.ShopService;
import com.hibiscusking.org.vo.ShopVo;
import com.hibiscusking.user.domain.Logininfo;
import com.hibiscusking.user.mapper.LogininfoMapper;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements ShopService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
//    @Autowired
//    private JavaMailSender javaMailSender;
    @Override
    public void settleIn(Shop shop) {
        Employee admin = shop.getAdmin();
        if (StringUtils.isBlank(shop.getName())) {
            throw new BussinessException("店铺名称不能为空");
        }
        if (StringUtils.isBlank(shop.getTel())) {
            throw new BussinessException("店铺电话不能为空");
        }
        if (StringUtils.isBlank(shop.getAddress())) {
            throw new BussinessException("店铺地址不能为空");
        }
        if (StringUtils.isBlank(admin.getUsername())) {
            throw new BussinessException("管理员账号不能为空");
        }
        if (StringUtils.isBlank(admin.getPhone())) {
            throw new BussinessException("管理员电话不能为空");
        }
        if (StringUtils.isBlank(admin.getEmail())) {
            throw new BussinessException("管理员邮箱不能为空");
        }


        //  百度ai判断
        if (!BaiduAuditUtils.TextCensor(shop.getName())) {
            throw new BussinessException("店铺名称不合规");
        }
        Shop tmpShop = shopMapper.findName(shop.getName());

        if (!BaiduAuditUtils.ImgCensor(shop.getLogo())) {
            throw new BussinessException("图片不合规");
        }
            // 判断是否是驳回后重新入驻
        System.out.println(shop.getId());
        if(shop.getId() == null) {
            if (tmpShop != null) {
                throw new BussinessException("店铺已存在");
            }
            Employee employee = employeeMapper.finEmpByPhone(admin.getPhone());
            if (employee != null && employee.getShopId() != null) {
                Shop shopMapperById = shopMapper.findById(employee.getShopId());
                if (shopMapperById.getAdminId().equals(employee.getId())) {
                    throw new BussinessException("管理员已经管理其他店铺");
                }
            }
            if (admin.getPassword() == null || !admin.getPassword().equals(admin.getComfirmPassword())) {
                throw new BussinessException("管理员密码不能为空且两次密码必须一致");
            }
            // 添加店铺
            shopMapper.add(shop);
            // 判断管理员是否为空，是空就添加员工
            if (employee == null) {
                employee = admin;
                // 设置盐值
                String salt = StrUtils.getComplexRandomString(32);
                // 把密码进行加密
                String pwd = salt + employee.getPassword(); // 密码加盐值
                String password = MD5Utils.encrypByMd5(pwd); // MD5加密
                employee.setPassword(password); // 密码
                employee.setSalt(salt); // 盐值
                Logininfo logininfo = new Logininfo();
                // 把emp赋值给loginfo
                BeanUtils.copyProperties(employee,logininfo);
                logininfo.setType(0);
                logininfoMapper.add(logininfo);
                employee.setLogininfoId(logininfo.getId());
                employeeMapper.add(employee);
            }
            employee.setShopId(shop.getId());
            // 给管理员添加店铺id
            employeeMapper.update(employee);
            // 给店铺添加管理员id
            shop.setAdminId(employee.getId());
            // 数据库修改店铺
            shopMapper.update(shop);
        } else {
            // 修改店铺信息
            shop.setState(0);
            shopMapper.update(shop);
        }

    }

    @Override
    public void approved(ShopAuditLog shopAuditLog) {
        Shop shop = new Shop();
        shop.setId(shopAuditLog.getShopId());
        shop.setState(1);
        shopMapper.update(shop);
        shopAuditLog.setAuditId(324);
        shopAuditLogMapper.add(shopAuditLog);

//        try {
//            // 1.创建复杂邮件对象
//            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//            // 2.发送复杂邮件的工具类
//            MimeMessageHelper helper = null;
//            helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
//            helper.setFrom("3151367884@qq.com");
//            helper.setSubject("店铺入驻审核通知");
//            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
//            helper.setText("<h1>恭喜你，店铺入驻审核通过，请点击下方链接激活店铺</h1>" +
//                    "http://localhost:8080/shop/audit/" + shopAuditLog.getShopId(),true);
//            // 4.添加附件
//            helper.addAttachment("感谢您.jpg",new File("N:\\0917idea\\文件\\学习资料\\56a39dc6-42a0-4152-92f1-cee114ced2b5 (1).jpg"));
//            // 5.设置收件人
//            helper.setTo("3151367884@qq.com");
//            // 6.发送邮件
//            javaMailSender.send(mimeMessage);
//        } catch (MessagingException e) {
//            throw new BussinessException("邮件发送失败");
//        }
        MailUtils.sendMail("3151367884@qq.com","恭喜你，店铺入驻审核通过，请点击下方链接激活店铺"  +
                  "http://localhost:8080/shop/audit/" + shopAuditLog.getShopId(),"店铺入驻审核通知");

    }
    /*
    激活店铺
     */
    @Override
    public void modifyState(Long id) {
        Shop shop = new Shop();
        shop.setId(id);
        shop.setState(2);
        shopMapper.update(shop);
    }

    @Override
    public void reject(ShopAuditLog shopAuditLog) {
        Shop shop = new Shop();
        shop.setId(shopAuditLog.getShopId());
        shop.setState(-1);
        shopMapper.update(shop);
        shopAuditLog.setAuditId(325);
        shopAuditLogMapper.add(shopAuditLog);
//        try {
//            // 1.创建复杂邮件对象
//            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//            // 2.发送复杂邮件的工具类
//            MimeMessageHelper helper = null;
//            helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
//            helper.setFrom("3151367884@qq.com");
//            helper.setSubject("店铺入驻审核通知");
//            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
//            helper.setText("<h1>"+ shopAuditLog.getNote() + "</h1>" +
//                    "http://localhost:8081/#/registerAgain?id="+shopAuditLog.getShopId(),true);
//            // 4.添加附件
//            helper.addAttachment("失败.jpg",new File("N:\\0917idea\\文件\\学习资料\\41460946_1084624958364654_2132497699650404352_n.jpg"));
//            // 5.设置收件人
//            helper.setTo("3151367884@qq.com");
//            // 6.发送邮件
//            javaMailSender.send(mimeMessage);
//        } catch (MessagingException e) {
//            throw new BussinessException("邮件发送失败");
//        }
        MailUtils.sendMail("3151367884@qq.com",shopAuditLog.getNote() + "请点击下方链接重新填写"  +
                "http://localhost:8081/#/registerAgain?id="+shopAuditLog.getShopId(),"店铺入驻审核通知");
    }

    @Override
    public Shop findShopAndEmpById(Long id) {
        return shopMapper.findShopAndEmpById(id);
    }

    @Override
    public void addShops(List<Shop> shops) {
        shopMapper.addShops(shops);
    }

    @Override
    public Map<String, Object> shopReportForm() {
        List<ShopVo> shopVo = shopMapper.shopReportForm();
        List<Integer> y = shopVo.stream().map(ShopVo::getCountNum).collect(Collectors.toList());
        List<Integer> x = shopVo.stream().map(ShopVo::getState).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        List<String> integers = new ArrayList<>();
        for (Integer stateX : x) {
            String s = ShopState.shopStateType(stateX);
            integers.add(s);
        }
        map.put("x",integers);
        map.put("y",y);
        return map;
    }

    @Override
    public PageList<Shop> queryByPage(BaseQuery baseQuery) {
        PageList<Shop> shopPageList = super.queryByPage(baseQuery);
        // 非空判断
        if (baseQuery == null){
            return shopPageList;
        }
        List<Shop> rows = shopPageList.getRows();
        List<Long> shopsId = rows.stream().map(Shop::getId).collect(Collectors.toList());
        List<ShopAuditLog> logList = shopAuditLogMapper.findByShopIds(shopsId);
        Map<Long, List<ShopAuditLog>> longListMap = logList.stream().collect(Collectors.groupingBy(ShopAuditLog::getShopId));
        rows.forEach(row->{
            row.setAuditLogs(longListMap.get(row.getId()));
        });
        return shopPageList;
    }

    @Override
    public void dele(Long id) {

    }
}
